import {useState} from "react";
import {NavLink, useNavigate} from "react-router";
import {Button, Form, Input, message, Typography} from "antd";
import {useUserState} from "../states/user.ts";
import {getUserInfo, login} from "../request/user.ts";
import FormItem from "antd/es/form/FormItem";

/**
 * This page is for displaying what is necessary for a user to log in.
 */
export default function Login() {
    const [username, setUsername] = useState<string>('')
    const [password, setPassword] = useState<string>('')
    const redirectTo = useNavigate();
    const userState = useUserState();
    const handleLogin = () => {

        login({username, password}).then(({data: response}) => {
            const loginStatus = response.body;
            if (loginStatus) {
                getUserInfo(username).then(({data: userInfo}) => {
                    userState.setUserInfo(userInfo.body)
                    console.log("设置成功")
                    redirectTo('/homePage/articleManagement')
                    message.success('登录成功').then(console.log)
                })
            } else {
                message.warning(response.statusCode, 2).then(console.log);
            }
        })
    }

    return (
        // 表单的 onSubmit 事件才是处理提交的正确位置
        <div className="w-[100vw] h-[100vh] flex flex-col justify-center items-center">
            <Typography.Title>登录</Typography.Title>
            <Form
                layout="vertical" // 或者 "horizontal"，根据需求选，horizontal 时 label 和输入框并排更常见
                className="w-1/4"
            >
                <FormItem
                    label={<span>用户名</span>}
                    required
                    labelAlign="right"
                >
                    <Input
                        value={username}
                        onChange={e => setUsername(e.target.value)}
                        placeholder="请输入用户名"
                    />
                </FormItem>

                <FormItem
                    label={<span>密码</span>}
                    required
                    labelAlign="right"
                >
                    <Input
                        type="password"
                        value={password}
                        onChange={e => setPassword(e.target.value)}
                        placeholder="请输入密码"
                    />
                </FormItem>
                <FormItem>
                    <div className="flex flex-col items-center">
                        <Button type="primary" htmlType="submit" onClick={handleLogin} size="large">登录</Button>
                        <NavLink to='/homePage'>去主页</NavLink>
                    </div>
                </FormItem>
            </Form>
        </div>
    )
}